package ar.uade.edu.fain.ad.server.dao.jpa;

import java.util.List;

import javax.persistence.PersistenceException;

import org.hibernate.Session;

import ar.uade.edu.fain.ad.server.business.Mesa;
import ar.uade.edu.fain.ad.server.business.MesaCompuesta;
import ar.uade.edu.fain.ad.server.business.MesaSimple;
import ar.uade.edu.fain.ad.server.business.Salon;
import ar.uade.edu.fain.ad.server.business.Sector;
import ar.uade.edu.fain.ad.server.dao.MesaDAO;
import ar.uade.edu.fain.ad.server.dao.SectorDAO;
import ar.uade.edu.fain.ad.server.dao.entity.MesaEntity;
import ar.uade.edu.fain.ad.server.dao.entity.SectorEntity;

public class SectorJpaDAO extends GenericJpaDAO<Sector, SectorEntity, Long>
		implements SectorDAO {

	private MesaDAO mesaDAO;

	public SectorJpaDAO() {
		super(SectorEntity.class);
	}

	public MesaDAO getMesaDAO() {
		return mesaDAO;
	}

	public void setMesaDAO(MesaDAO mesaDAO) {
		this.mesaDAO = mesaDAO;
	}

	@Override
	protected SectorEntity toEntity(Sector business) {
		return null;
	}

	@Override
	protected Sector toBusiness(final SectorEntity entity) {
		final Sector sector = new Sector();
		sector.setId(entity.getId());
		sector.setNombre(entity.getNombre());
		Salon salon = new Salon();
		salon.setId(entity.getSalon().getId());
		sector.setSalon(salon);
		for (MesaEntity mesaEntity : entity.getMesas()) {
			final Mesa mesa = getMesaDAO().get(mesaEntity.getId());
			if (mesa instanceof MesaCompuesta) {
				sector.getMesasCompuestas().add((MesaCompuesta) mesa);
			} else {
				sector.getMesasSimples().add((MesaSimple) mesa);
			}
		}
		return sector;
	}

	@Override
	public List<Sector> buscarSectoresDe(final Long idSalon) {
		return execute(new Query<List<Sector>>() {
			@Override
			public List<Sector> inTransaction(Session session)
					throws PersistenceException {
				@SuppressWarnings("unchecked")
				final List<SectorEntity> entities = 
						session.getNamedQuery("sector.bySalon")
								.setParameter("idSalon", idSalon)
								.list();
				return toBusiness(entities);
			}
		});
	}
	
}
